// Package routes 路由器
package routes

import (
	"ginmin/configs"
	"ginmin/middleware"
	"ginmin/routes/controllers"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

// RegisterRoutes 注册路由
func RegisterRoutes(router *gin.Engine) {
	//初始化session
	ServerConfig := configs.GetServerConfig()
	store := cookie.NewStore([]byte(ServerConfig["HashIDSalt"]))
	store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"})
	router.Use(sessions.Sessions("ginmin-session", store))

	//跨域中间件
	//router.Use(Cors())
	//waf拦截中间件
	router.Use(middleware.AntiSQLInjectMiddleWare("intercept"))

	//静态文件目录
	router.StaticFS("/static", gin.Dir("./assets", false))
	router.StaticFile("/favicon.ico", "./assets/favicon.ico")
	router.StaticFS("/uploads", gin.Dir("./uploads", false)) //上传文件目录

	//首页
	router.GET("/", controllers.IndexHome)
	router.GET("/index", controllers.IndexHome)
	api := router.Group("/")
	api.Use(middleware.AuthRequired())
	{

	}

	//404
	/*router.NoRoute(func(c *gin.Context) {
	    c.HTML(200, "index/404.html", gin.H{
	        "title": "页面未找到",
	    })
	})*/
}

// Cors 跨域中间件
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		if method == "OPTIONS" {
			c.AbortWithStatus(204)
		}
		c.Next()
	}
}
